<template>
  <div class="box_wrap">
    <div class="box_wrap_title">
      个人信息
    </div>
    <el-form ref="refPersonalInfo" :model="vo" :rules="rules" size="medium" label-width="120px">

      <el-row>
        <el-col :span="12">
          <div class="gl_clear">
            <div class="personalUserInfo_img_wrap gl_fl">
              <el-form-item align="center" prop="imagePath">
                <el-input v-show="false" v-model.trim="vo.imagePath" />
                <el-dialog class="gl_dialog_TitleLine" width="880px" title="上传图片" :append-to-body="true" :visible.sync="photoCropperVisible" :close-on-click-modal="false" :close-on-press-escape="false">
                  <photo-cropper ref="photoCropper" :action="action" :option="photoCropperOption" height="375px" @photoCropperSave="photoCropperSave" />
                </el-dialog>
                <!-- <div class="upload_game_img" :class="isEdit === 'EDIT' ? '' : 'no_pointer'" @click="openPhotoCropper"> -->
                <template v-if="!checkMode">
                  <div class="upload_game_img" @click="openPhotoCropper">
                    <img v-if="vo.imagePath" class="show_img" :src="getStaticFileUrl(vo.imagePath)">
                    <!-- <i v-if="!vo.imagePath && isEdit === 'EDIT'" class="el-icon-plus" /> -->
                    <i v-if="!vo.imagePath" class="el-icon-plus" />
                  </div>
                </template>
                <template v-else>
                  <div class="upload_game_img no_pointer">
                    <img v-if="vo.imagePath" class="show_img" :src="getStaticFileUrl(vo.imagePath)">
                    <!-- <i v-if="!vo.imagePath && isEdit === 'EDIT'" class="el-icon-plus" /> -->
                    <i v-if="!vo.imagePath" class="el-icon-plus" />
                  </div>
                </template>
              </el-form-item>
            </div>
            <div v-if="!checkMode" class="photo_tips gl_fl">
              <p class="tip_info_style">请上传近期彩色免冠照片</p>
              <p class="tip_info_style">文件格式：jpg、jpeg、png</p>
              <p class="tip_info_style">照片大小不能超过3M</p>
            </div>
          </div>
        </el-col>
        <el-col :span="12">
          <el-row>
            <el-col :span="24">
              <el-form-item label="姓名" prop="name">
                <template v-if="!checkMode">
                  <el-input v-if="isEdit === 'EDIT'" v-model.trim="vo.name" placeholder="请输入姓名" type="text" />
                  <span v-else>{{ vo.name }}</span>
                </template>
                <template v-else>
                  <span>{{ vo.name }}</span>
                </template>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="证件类型" prop="idCardTypeCode">
                <template v-if="!checkMode">
                  <el-select v-if="isEdit === 'EDIT'" v-model="vo.idCardTypeCode" placeholder="请选择证件类型" style="width: 100%" @change="clicktypecode">
                    <el-option v-for="item in dict.idCardType" :key="item.code" :label="item.value" :value="item.code" />
                  </el-select>
                  <span v-else>{{ findDictDataByCode('idCardType', vo.idCardTypeCode).value }}</span>
                </template>
                <template v-else>
                  <span>{{ findDictDataByCode('idCardType', vo.idCardTypeCode).value }}</span>
                </template>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="证件号码" prop="idCardNumber" :rules="vo.idCardTypeCode === 'IdCard' ? formRules.idCard : formRules.unIdCard">
                <template v-if="!checkMode">
                  <el-input v-if="isEdit === 'EDIT'" v-model.trim="vo.idCardNumber" placeholder="请输入证件号码" type="text" @input="computGenderAndBirth" />
                  <span v-else>{{ vo.idCardNumber }}</span>
                </template>
                <template v-else>
                  <span>{{ vo.idCardNumber }}</span>
                </template>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="性别" prop="genderCode">
                <template v-if="!checkMode">
                  <el-select v-if="isEdit === 'EDIT'" v-model="vo.genderCode" placeholder="请选择性别" style="width: 100%">
                    <el-option v-for="item in dict.dictGender" :key="item.code" :label="item.value" :value="item.code" />
                  </el-select>
                  <span v-else>{{ findDictDataByCode('dictGender', vo.genderCode).value }}</span>
                </template>
                <template v-else>
                  <span>{{ findDictDataByCode('dictGender', vo.genderCode).value }}</span>
                </template>
              </el-form-item>
            </el-col>
          </el-row>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="12">
          <el-form-item label="国籍" prop="nationality">
            <template v-if="!checkMode">
              <el-select v-if="isEdit === 'EDIT'" v-model="vo.nationality" placeholder="请选择国籍" filterable style="width: 100%" @change="onChangeNationality">
                <el-option v-for="item in dict.country" :key="item.code" :label="item.value" :value="item.code" />
              </el-select>
              <span v-else>{{ findDictDataByCode('country', vo.nationality).value }}</span>
            </template>
            <template v-else>
              <span>{{ findDictDataByCode('country', vo.nationality).value }}</span>
            </template>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="出生日期" prop="birthDate">
            <template v-if="!checkMode">
              <el-date-picker v-if="isEdit === 'EDIT'" v-model="vo.birthDate" type="date" value-format="yyyy-MM-dd" placeholder="请选择出生日期" :clearable="false" style="width: 100%" />
              <span v-else>{{ vo.birthDate ? vo.birthDate.slice(0, 10) : '' }}</span>
            </template>
            <template v-else>
              <span>{{ vo.birthDate ? vo.birthDate.slice(0, 10) : '' }}</span>
            </template>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="12">
          <el-form-item label="民族" prop="national">
            <template v-if="!checkMode">
              <el-select v-if="isEdit === 'EDIT'" v-model="vo.national" placeholder="请选择民族" style="width: 100%">
                <el-option v-for="item in filterNationDict" :key="item.code" :label="item.value" :value="item.code" />
              </el-select>
              <span v-else>{{ findDictDataByCode('nation', vo.national).value }}</span>
            </template>
            <template v-else>
              <span>{{ findDictDataByCode('nation', vo.national).value }}</span>
            </template>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="手机号码" prop="phoneNumber">
            <template v-if="!checkMode">
              <el-input v-model.trim="vo.phoneNumber" placeholder="请输入联系人手机号" type="text" />
            </template>
            <template v-else>
              <span>{{ vo.phoneNumber }}</span>
            </template>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="所在地区" prop="provinceCode">
            <template v-if="!checkMode">
              <el-cascader v-model="vo.addressData" size="mini" :options="cache.district" :props="{ value: 'code', label: 'name' }" placeholder="请选择省市区" style="width: 100%;" @change="onChangeAddressData" />
            </template>
            <template v-else>
              <span class="gl_mr_5">{{ findDictDataByCode('district', vo.addressData[0]).value }}</span>
              <span class="gl_mr_5">{{ findDictDataByCode('district', vo.addressData[1]).value }}</span>
              <span class="gl_mr_5">{{ findDictDataByCode('district', vo.addressData[2]).value }}</span>
            </template>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="详细地址" prop="address">
            <template v-if="!checkMode">
              <el-input v-model.trim="vo.address" placeholder="请输入详细地址" type="text" />
            </template>
            <template v-else>
              <span>{{ vo.address }}</span>
            </template>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="24">
          <div class="gl_clear">
            <div class="gl_fl">
              <el-form-item label="实名认证" style="width:370px" :prop="vo.idCardTypeCode!='IdCard'?'idCardImage':''">
                <upload-file
                  v-if="!checkMode"
                  ref="uploadFile"
                  class="imgt_upload"
                  :file-name="'证件照正面'"
                  :action="action"
                  :show-file-list="false"
                  :limit="1"
                  file-type="image"
                  format-file=".jpg,.jpeg,.png"
                  :default-file-url="getStaticFileUrl(vo.idCardImage)"
                  @uploadSuccess="photoSavePositive"
                />
                <img v-else class="certificate_show_img" :src="getStaticFileUrl(vo.idCardImage)">
              </el-form-item>
            </div>
            <div class="gl_fl">
              <el-form-item label="" label-width="20px" style="width:260px">
                <upload-file
                  v-if="!checkMode"
                  ref="uploadFile"
                  class="imgt_upload"
                  :file-name="'证件照反面'"
                  :action="action"
                  :show-file-list="false"
                  :limit="1"
                  file-type="image"
                  format-file=".jpg,.jpeg,.png"
                  :default-file-url="getStaticFileUrl(vo.idCardBackImage)"
                  @uploadSuccess="photoSaveBack"
                />
                <img v-else class="certificate_show_img" :src="getStaticFileUrl(vo.idCardBackImage)">
              </el-form-item>
            </div>
          </div>
        </el-col>
      </el-row>

    </el-form>
  </div>
</template>

<script>
import { mapState } from 'vuex';
import { CopyData } from '@/lib';
import validator from '@/lib/validate';

import uploadFile from './uploadFileDialog';
import photoCropper from '@/components/PhotoCropper';

import { PersonalUserInfoForTrainVO_Rules } from '@/lib/validate/myCenter';

import { SiSTKWEventsManagementRegisterDto } from '@/lib/form/train/swaggerForm.js';

export default {
  components: {
    photoCropper,
    uploadFile
  },
  props: {
    dict: {
      type: Object,
      default() {
        return {};
      }
    },
    // 传入的个人信息数据
    userData: {
      type: Object,
      default() {
        return {};
      }
    },
    checkMode: { // 强制查看模式，优先级大于isEdit
      type: Boolean,
      default: false
    }
  },
  data () {
    return {
      vo: new SiSTKWEventsManagementRegisterDto(),
      isEdit: 'CHECK', // CHECK | EDIT
      rules: new PersonalUserInfoForTrainVO_Rules(), // 数据验证规则
      formRules: {
        idCard: [
          { required: true, message: '请输入证件号码', trigger: 'blur' },
          {
            validator(rule, value, callback) {
              callback(validator.checkIdNumber(value, '身份证号码格式错误'));
            },
            trigger: 'blur'
          }
        ],
        unIdCard: [
          { required: true, message: '请输入证件号码', trigger: 'blur' }
        ]
      },
      action: `${WEB_CONFIG.VUE_APP_STATIC_FILE_RUL}/api/upload/image`, // 图片上传地址
      photoCropperVisible: false, // 上传图片窗口的显示与隐藏
      photoCropperOption: {
        img: '',
        autoCropWidth: '200px',
        autoCropHeight: '280px',
        enlarge: 1,
        fixedNumber: [200, 280]
      }
    };
  },
  computed: {
    ...mapState({
      cache: state => state.dict.cache
    }),
    filterNationDict() {
      if (this.vo.nationality === 'CHN') {
        // 57 表示其他
        const _nation = this.dict.nation || [];
        return _nation.filter(item => item.code !== '57');
      } else {
        return [{ code: '57', value: '其他' }];
      }
    }
  },
  watch: {
    userData: {
      immediate: true,
      deep: true,
      handler(val) {
        if (val.isApproved) {
          this.isEdit = 'CHECK';
        } else {
          this.isEdit = 'EDIT';
        }
        this.init();
      }
    }
  },
  methods: {
    // 初始化数据
    init () {
      CopyData(this.userData, this.vo);
      this.vo.addressData = [this.userData.provinceCode, this.userData.cityCode, this.userData.countyCode];
      this.$nextTick(() => {
        this.$refs.photoCropper && this.$refs.photoCropper.init();
        this.$refs.refPersonalInfo.clearValidate();
      });
    },
    clicktypecode() {
      this.$refs.refPersonalInfo.clearValidate('idCardImage');
      this.$refs.refPersonalInfo.clearValidate('idCardBackImage');

    },
    // 外部获取组件数据的方法
    getInsideUserData () {
      return new Promise((reslove, reject) => {
        this.$refs.refPersonalInfo.validate((valid) => {
          if (valid) {
            reslove(this.vo);
          } else {
            reject(null);
          }
        });
      });
    },
    // 清空数据及验证
    clearInsideUserData () {
      this.insideUserData = new SiSTKWEventsManagementCreateRegisterWithTagsInput();
      this.$refs.refPersonalInfo.resetFields();
    },
    // 选择国籍
    onChangeNationality (val) {
      console.log('val: ', val);
      this.vo.national = '';
    },
    // 根据code在相应字典中寻找数据
    findDictDataByCode (dictKey, code) {
      const _dict = this.dict[dictKey];
      if (_dict) {
        return _dict.find(item => item.code === code) || {};
      } else {
        console.log('findDictDataByCode -> findDictDataByCode: ' + dictKey + ', 未找到字典数据.');
        return {};
      }
    },
    // 根据身份证号码计算性别及生日
    computGenderAndBirth () {
      const _idCardNum = this.vo.idCardNumber;
      const _reg = /^[1-9][0-9]{5}(19|20)[0-9]{2}((01|03|05|07|08|10|12)(0[1-9]|[1-2][0-9]|3[0-1])|(04|06|09|11)(0[1-9]|[1-2][0-9]|30)|02(0[1-9]|[1-2][0-9]))[0-9]{3}([0-9]|x|X)$/;
      // 当证件类型为身份证 且 证件号码不为空 且 通过身份证校验时。自动设置性别和出生日期
      if (_reg.test(_idCardNum)) {
        const _genderNum = _idCardNum.slice(-2, -1);
        this.vo.genderCode = _genderNum % 2 === 0 ? 'W' : 'M';
        this.vo.birthDate = _idCardNum.slice(6, 10) + '-' + _idCardNum.slice(10, 12) + '-' + _idCardNum.slice(12, 14);
      }
    },
    // 点击打开照片裁剪窗口
    openPhotoCropper () {
      // if (this.isEdit === 'EDIT') { // 根据bug3224要求，此处可随意更换照片
      if (this.vo['imagePath']) {
        this.$set(this.photoCropperOption, 'img', this.getStaticFileUrl(this.vo['imagePath']));
      }
      this.photoCropperVisible = true;
      // }
    },
    // 点击保存照片裁剪窗口
    photoCropperSave (uploadImg) {
      this.$refs.photoCropper.upload()
        .then(res => {
          this.$set(this.vo, 'imagePath', res.tempUrl);
          this.photoCropperVisible = false;
        });
    },
    photoSavePositive (fileUrl) {
      this.$set(this.vo, 'idCardImage', fileUrl.tempUrl);
    },
    photoSaveBack (fileUrl) {
      this.$set(this.vo, 'idCardBackImage', fileUrl.tempUrl);
    },
    // 获取静态文件
    getStaticFileUrl (relativeUrl) {
      if (!relativeUrl) return '';
      return WEB_CONFIG.VUE_APP_STATIC_FILE_RUL + relativeUrl;
    },
    // 更改所在地区，将信息传入需要的Code中
    onChangeAddressData () {
      const _addressData = this.vo.addressData;
      this.vo.provinceCode = _addressData ? _addressData[0] || '' : '';
      this.vo.cityCode = _addressData ? _addressData[1] || '' : '';
      this.vo.countyCode = _addressData ? _addressData[2] || '' : '';
    }
  }
};
</script>

<style>
  .personalUserInfo_img_wrap .el-form-item__error {
    padding-left: 10px;
  }
  .personalUserInfo .el-form-item__error{
    padding-top: 0;
    margin-top: -4px;
  }
  .personalUserInfo .reset_address_error .el-form-item__error {
    margin-top: 2px;
  }
</style>

<style lang="scss" scoped>
  .tip_info_style {
    padding: 0 10px 0 30px;
    font-size: 14px;
    color: #C0C4CC;
  }

  .upload_game_img.no_pointer {
    cursor: default;
  }
  .upload_game_img {
    width: 150px;
    height: 210px;
    line-height: 205px;
    text-align: center;
    font-size: 20px;
    border: 1px dotted #DCDFE6;
    border-radius: 4px;
    cursor: pointer;
    transition: all 0.2s ease;
    position: relative;
    // margin: 10px 0;
  }
  .upload_game_img .show_img {
    max-width: 100%;
    max-height: 100%;
    border-radius: 4px;
    vertical-align: middle;
  }
  .photo_tips {
    height: 210px;
    display: flex;
    flex-direction: column;
    justify-content: flex-end;
  }

  .imgt_upload {
    width: 240px;
    height: 150px;
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    overflow: hidden;
  }
  .imgt_upload.no_pointer {
    cursor: default;
  }
  .imgt_upload:hover {
    border-color: #409EFF;
  }
  .certificate_show_img {
    width: 240px;
    height: 150px;
    border-radius: 4px;
    vertical-align: middle;
  }
</style>
